import { isIos, isAndroid } from './utils';
import { log, error, warn } from './log';

function noop() {}

// 这里只有第一次去调用的时候才跳转页面，否则不做任何加载操作
// fix恒易贷的bug，如果是老的webview的话加载wvjbscheme://__BRIDGE_LOADED__ 会报错
let currentPromise;
const getBridge = function() {
  if(currentPromise) {
    return currentPromise;
  }
  currentPromise = new Promise((resolve) => {
    setupWebViewJavascriptBridge((bridge) => {
      // resolve这个function
      resolve(bridge);
    });
  });
};

function setupWebViewJavascriptBridge(callback) {
  if (isIos()) {
    if (window.WebViewJavascriptBridge) { return callback(window.WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    const WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(() => { document.documentElement.removeChild(WVJBIframe); }, 0);
  }
  if (isAndroid()) {
    if (window.WebViewJavascriptBridge) {
      callback(window.WebViewJavascriptBridge);
    } else {
      document.addEventListener('WebViewJavascriptBridgeReady', () => {
        callback(window.WebViewJavascriptBridge);
      }, false);
    }
  }
}

export function postMessage(def, payload = {}, fnc = noop) {
  // // 判断方法名称
  if (!def || typeof def !== 'string') {
    throw new Error(`postMessage的方法名应该是不为空的string，不能是${def}`);
  }
  // 判断回调函数合法
  if (typeof fnc !== 'function') {
    warn(`postMessage的第三个参数应该是function，不应该是${fnc}`);
    fnc = noop;
  }
  // 判断数据类型(null)
  if (payload === null) {
    warn('not expect null when use callHandler, use \'\' instead');
  } else if (!['string', 'object'].includes(typeof payload)) { // 非法类型
    warn(`callhandler should not use ${typeof payload} type, please check it`);
  }
  return new Promise((resolve, reject) => {
    getBridge().then((bridge) => {
      if (isAndroid()) {
        try{
          bridge.init(() => {});
        } catch(e) {
          // empty block
        }
        payload = typeof payload === 'string' ? payload : JSON.stringify(payload);
      }
      bridge.callHandler(def, payload, fnc);
      resolve();
    }).catch((e) => {
      warn(e, '原生调用', `${def}`);
    });
  });
}

export function getMessage(def, func = noop) {
  // 判断方法名称
  if (!def || typeof def !== 'string') {
    throw new Error(`getMessage的方法名应该是不为空的string，不能是${def}`);
  }

  // 判断回调函数合法
  if (typeof func !== 'function') {
    warn(`getMessage的第二个参数应该是function，不应该是${func}`);
    func = noop;
  }

  return new Promise((resolve, reject) => {
    getBridge().then((bridge) => {
      try{
        isAndroid() && bridge.init(() => {});
      } catch(e) {
        // empty block
      }
      bridge.registerHandler(def, (data) => {
        try {
          data = JSON.parse(data);
        } catch(e){
          // empty block
        }
        func && func(data);
      });
      resolve();
    }).catch((e) => {
      warn(e);
    });
  });
}

// 初始化记载bridge
export function loadBridge() {
  getBridge();
}

export default {
  postMessage,
  getMessage,
  loadBridge,
};
